package cn.tedu.weibo2.controller;


import cn.tedu.weibo2.base.response.JsonResult;
import cn.tedu.weibo2.base.response.StatusCode;
import cn.tedu.weibo2.mapper.UserMapper;
import cn.tedu.weibo2.pojo.dto.UserLoginDTO;
import cn.tedu.weibo2.pojo.dto.UserRegDTO;
import cn.tedu.weibo2.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("v1/users/")
@Api(tags = "用户模块")
public class UserController {
    @Autowired(required = false)
    private UserMapper userMapper;


    @PostMapping("reg")
    @ApiOperation(value = "注册")
    public JsonResult reg(@RequestBody UserRegDTO userRegDTO){
        UserVO userVO=userMapper.selectByUsername(userRegDTO.getUsername());
        if (userVO==null){
            int i = userMapper.insertUser(userRegDTO);
            if (i==1)
                return JsonResult.ok();
            return JsonResult.notok();
        }
        return new JsonResult(StatusCode.USERNAME_ALREADY_EXISTS);
    }



    @PostMapping("login")
    @ApiOperation(value = "登录")
    public JsonResult  login(@RequestBody UserLoginDTO userLoginDTO,@ApiIgnore HttpSession session){
        UserVO userVO=userMapper.selectByUsername(userLoginDTO.getUsername());
        if (userVO!=null){
            if (userVO.getPassword().equals(userLoginDTO.getPassword())){
                session.setAttribute("user",userVO);
                 return JsonResult.ok();
            }
            return new JsonResult(StatusCode.PASSWORD_ERROR);
        }
        return new JsonResult(StatusCode.USERNAME_ERROR);
    }


    @GetMapping("currentUser")
    @ApiOperation(value = "获取当前用户")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        return JsonResult.ok(session.getAttribute("user"));
    }



    @GetMapping("logout")
    @ApiOperation(value = "退出登录")
    public JsonResult logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return JsonResult.ok();
    }


}
